package com.wbp.cms.client.util;

import java.util.ArrayList;
import java.util.List;


public class BitUtils {

  final static char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c',
      'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
      'v', 'w', 'x', 'y', 'z'};

  /**
   * 将输入的位数置为0，其他都是1
   * 
   * @param bits
   * @return
   */
  public static long unmaskBits(Integer... bits) {
    return ~maskBits(bits);
  }

  /**
   * 将输入的位数置为1，其他都是0
   * 
   * @param bits
   * @return
   */
  public static long maskBits(Integer... bits) {
    long result = 0;
    for (int bit : bits) {
      if (bit > 63 || bit < 0) {
        throw new IllegalArgumentException("bit is larger than 63 or less than 0");
      }
      result += 1L << bit;
    }
    return result;
  }

  /**
   * 获取为1的位数
   * 
   * @param input
   * @return
   */
  public static List<Integer> getMaskedBits(long input) {
    List<Integer> result = new ArrayList<Integer>();
    for (int i = 0; i < 64 && input != 0; i++) {
      if ((input & 1L) > 0) {
        result.add(i);
      }
      input >>>= 1;
    }

    return result;
  }

  /**
   * 检查输入的值位数是不是为1
   * 
   * @param input
   * @param bit
   * @return
   */
  public static boolean checkBit(long input, int bit) {
    long mask = maskBits(bit);
    return (input & mask) > 0;
  }

  /**
   * 输出2进制字符串
   * 
   * @param i
   * @return
   */
  public static String toBinaryString(long i) {
    return toUnsignedString(i, 1);
  }

  private static String toUnsignedString(long i, int shift) {
    char[] buf = new char[64];
    int charPos = 64;
    int radix = 1 << shift;
    long mask = radix - 1;
    do {
      buf[--charPos] = digits[(int) (i & mask)];
      i >>>= shift;
    } while (i != 0);

    return new String(buf, charPos, (64 - charPos));
  }
}
